package org.example.reactor;

import org.example.utils.LogUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class EchoClient {
    public static void main(String[] args) throws Exception{
        new Thread(new EchoClientThread()).start();
    }

    public static class EchoClientThread implements Runnable {

        private ByteBuffer buffer = ByteBuffer.allocate(1024);

        private Selector selector;

        private SocketChannel sch;

        public EchoClientThread() {
            try {
                this.selector = Selector.open();
                sch = SocketChannel.open();
                sch.configureBlocking(false);
                sch.connect(new InetSocketAddress("localhost", 8081));
                sch.register(selector, SelectionKey.OP_CONNECT);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                Scanner scanner = new Scanner(System.in);
                while (selector.select() > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        buffer.clear();
                        SelectionKey sk = iterator.next();
                        if (sk.isConnectable()) {
                            if (sch.finishConnect()) {
                                sch.configureBlocking(false);
                                sk.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                                LogUtils.info("服务端连接成功");
                            }
                            else {
                                LogUtils.info("服务端连接失败");
                            }
                        }
                        else if (sk.isWritable()) {
                            LogUtils.info("请输入内容：");
                            if (scanner.hasNext()) {
                                buffer.put(scanner.next().getBytes());
                                buffer.flip();
                                sch.write(buffer);
                                buffer.clear();
                                // 写完之后需要取消写事件，否则会一直处于写状态
//                                sk.interestOps(SelectionKey.OP_READ);
                            }
                            sk.interestOps(SelectionKey.OP_READ);
                        }
                        else if (sk.isReadable()) {
                            int num = -1;
                            SocketChannel skChannel = (SocketChannel) sk.channel();
                            while ((num = skChannel.read(buffer)) > 0) {
                                buffer.flip();

                                byte[] contents = new byte[num];
                                buffer.get(contents);
                                LogUtils.info(new String(contents));
                                buffer.clear();
                            }
                            sk.interestOps(SelectionKey.OP_WRITE);
                        }

                        iterator.remove();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
